//
//  MusicPlayViewController.m
//  LO_MUSIC
//
//  Created by lanou3g on 16/2/26.
//  Copyright © 2016年 徐强. All rights reserved.
//

#import "MusicPlayViewController.h"
#import "RequestUrl.h"
#import "AudioPlayer.h"
#import "lyricHelper.h"
static MusicPlayViewController *MPVC = nil;
@interface MusicPlayViewController ()<AudioPlayerDelegate,UITableViewDataSource,UITableViewDelegate>
//音乐播放器
@property (nonatomic ,strong)AudioPlayer *audioPlayer;

@end

@implementation MusicPlayViewController
//创建界面使用单例
+ (instancetype )shareMusicPlayViewController
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        MPVC = [[MusicPlayViewController alloc]init];
    });
    return MPVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setDelegate];
    [self initView];
    [self sliderAddAction];
    
}
- (void)setDelegate{
    self.audioPlayer.delegate = self;
    self.lyricTableView.delegate = self;
    self.lyricTableView.dataSource = self;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //如果点击的歌曲与当前一致，则不操作直接返回
    if (self.currentIndex == self.index) {
        return;
    }
    //否则修改currentIndex的值
    self.currentIndex = self.index;
    //刚进来这个界面的时候就开始播放歌曲
    [self beginPlay];
}
#pragma mark - 界面初始化
- (void)initView{
    //图片以圆显示
    self.imV.layer.cornerRadius = 110;
    self.imV.layer.masksToBounds = YES;
    /*
     self.automaticallyAdjustsScrollViewInsets = NO;
     看这个UIViewController的这个属性你就明白了，此属性默认为YES，这样UIViewController下如果只有一个UIScollView或者其子类，那么会自动留出空白，让scollview滚动经过各种bar下面时能隐约看到内容。但是每个UIViewController只能有唯一一个UIScollView或者其子类，如果超过一个，需要将此属性设置为NO,自己去控制留白以及坐标问题。
     */
    self.automaticallyAdjustsScrollViewInsets = NO;
    
//    self.navigationController.navigationBar.translucent = NO;
}
#pragma mark - 滑块绑定事件
- (void)sliderAddAction{
    [self.currentTimeSlider addTarget:self action:@selector(sliderAction:) forControlEvents:(UIControlEventValueChanged)];
    [self.volumeSlider addTarget:self action:@selector(volumeAction:) forControlEvents:UIControlEventValueChanged];
}
#pragma mark - 拖拽进度条改变歌曲进度
- (void)sliderAction:(UISlider *)sender{
    // 修改播放器的播放事件
    [self.audioPlayer seekToTime:self.currentTimeSlider.value];
}
- (void)volumeAction:(UISlider *)sender{
    //用音量进度条调节音量
    self.audioPlayer.volume = self.volumeSlider.value;
}
#pragma mark - AudioPlayerDelegate
- (void)playFinish
{
    //播放完就播放下一曲
    [self NextMusic:nil];
    //进度条归零
    self.currentTimeSlider.value = 0;
}
//每0.1s调用一次
- (void)playWithTime:(CGFloat )time{
    self.currentTimeSlider.value += 0.1;
    //播放时间
    self.playedTimeLabel.text = [self timeStrFromTime:self.currentTimeSlider.value];
    //剩余时间
    self.restTimeLabel.text = [self timeStrFromTime:self.currentTimeSlider.maximumValue - self.currentTimeSlider.value];
    //图片旋转
    self.imV.transform = CGAffineTransformRotate(self.imV.transform, M_PI / 180);
    
    
    //对应歌词
    //获取当前歌词的下标
    NSInteger inde = [[lyricHelper shareLyricHelper] indexForTime:time];
    if (inde>0) {
        self.currentingIndex = [NSIndexPath indexPathForRow:inde inSection:0];
        [self.lyricTableView reloadData];
    //每次让当前歌词所在的cell在屏幕的中间
        [self.lyricTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:inde inSection:0] atScrollPosition:(UITableViewScrollPositionMiddle) animated:YES];
    }
}

//时间变成字符串
- (NSString *)timeStrFromTime:(CGFloat )time{
    NSInteger minu = time / 60;
    NSInteger second = (NSInteger)time % 60;
    return [NSString stringWithFormat:@"%02ld :%02ld",minu,second];
}

#pragma mark - 停止音乐
- (IBAction)stopMusic:(UIButton *)sender {
    [self.audioPlayer stop];
    self.currentTimeSlider.value = 0;
}
#pragma mark - 暂停／播放
- (IBAction)pauseOrResume:(UIButton *)sender {
    [self.audioPlayer playOrPause];
}
#pragma mark - 上一曲
- (IBAction)lastMusic:(UIButton *)sender {
    
    if (self.currentIndex >= 1) {
        self.currentIndex --;
    }else{
        //若当前播放为第一首歌时，上一曲播放最后一曲
        self.currentIndex = self.arrAllMusic.count-1;
    }
    //换歌曲的时候图片都从头旋转
    self.imV.transform = CGAffineTransformMakeRotation(0);
    [self beginPlay];
}
#pragma mark - 下一曲
- (IBAction)NextMusic:(UIButton *)sender {
    //如果当前是最后一首歌，点击下一曲则播放第一首歌
    if (self.currentIndex == self.arrAllMusic.count) {
        self.currentIndex = 0;
    }else{
        //否则播放下一曲
        self.currentIndex ++;
    }
    //换歌曲的时候图片都从头旋转
    self.imV.transform = CGAffineTransformMakeRotation(0);
    [self beginPlay];
}
#pragma mark - 开始播放音乐
- (void)beginPlay{
    MusicModel *model = self.arrAllMusic[self.currentIndex];
    //处理歌词
    lyricHelper *lyHelper = [lyricHelper shareLyricHelper];
    [lyHelper lyricWithStr:model.lyric];
    //进度条归零
    self.currentTimeSlider.value = 0;
    self.title = model.name;
    //每次播放前便修改进度条的最大值
    self.currentTimeSlider.maximumValue = model.duration/1000;
    //总时间
    self.restTimeLabel.text = [self timeStrFromTime:model.duration * 1.0 /1000];
    //下载图片
    self.imV.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.picUrl]]];
    //播放音乐
    [self.audioPlayer playWithUrl:model.mp3Url];
}
#pragma mark - 下载音乐
- (IBAction)downCurrentMusic:(UIButton *)sender {
    //先弹出一个提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"无法下载此歌曲" preferredStyle:(UIAlertControllerStyleAlert)];
    [self presentViewController:alert animated:YES completion:^{
        sleep(1);
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
}
#pragma mark - tableViewde 代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [lyricHelper shareLyricHelper].modelArr.count;
}
- (CGFloat )tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"UITableViewCell"];
    }
    lyricHelper *model = [lyricHelper shareLyricHelper].modelArr[indexPath.row];
    cell.backgroundColor = [UIColor grayColor];
    cell.textLabel.text = model.lyric;
    //歌词不会居中
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    if (self.currentingIndex == indexPath) {
        //当前歌词的时候相应的歌词产生相应的变化
        cell.textLabel.font = [UIFont systemFontOfSize:21];
        cell.textLabel.textColor = [UIColor blueColor];
        
    }else{
        //不是当前歌词的时候还原产生相应的变化
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        cell.textLabel.textColor = [UIColor blackColor];
    }
    
    return cell;
}

#pragma mark - 懒加载
- (AudioPlayer *)audioPlayer{
    if (!_audioPlayer) {
        _audioPlayer = [AudioPlayer shareAudioPlayer];
    }
    return _audioPlayer;
}

@end
